import React, {useEffect} from "react";
import {PageLoading} from "@ant-design/pro-layout";
import {useParams, useSearchParams} from "react-router-dom";
import dd from "dingtalk-jsapi";

import {useNavigate} from "react-router-dom";
import {currentUser, login} from "@/services/login.ts";
import {message} from "antd";
import initialStatesAtom from "@/store/initialStatesAtom";
import {useStore} from "jotai/index";

/**
 * 三方登陆回掉
 * @constructor
 */
const SocialCallbackLogin: React.FC = () => {
    const navigate = useNavigate();
    const store = useStore();
    const {source} = useParams();
    const [searchParams]= useSearchParams()
    const socialCode = searchParams.get('code')
    const state = searchParams.get('state')
    const corpId = searchParams.get('corpId')
    const tenantId = searchParams.get('tenantId') || '000000'
    const redirect_uri = searchParams.get('redirect_uri') || '/'
    console.log(socialCode,state,corpId,redirect_uri);
    const fetchUserInfo = async () => {
        const userInfo = await currentUser();
        console.log('---fetchUserInfo--',userInfo)
        store.set(initialStatesAtom,{currentUser:userInfo.data.data,isAuthenticated:true})
    };
    const handleSocialLogin =async (values:any) =>{
        console.log('---handleSocialLogin begin---')
        const {data,status} = await login({ ...values, grantType:'social',clientId:import.meta.env.VITE_CLIENT_ID });
        console.log('---handleSocialLogin end---',data,status)
        if (status === 200 && data.code === 200) {
            localStorage.setItem('token', data.data.access_token);
            await fetchUserInfo();
            navigate(redirect_uri, { replace: true });
            message.success("登录成功");
            return;
        }
        console.log(data.data);
        message.error(data.msg);
        navigate(`/result/${data.code}/${data.code}/${data.msg}`, { replace: true })
    }
    useEffect(() => {
        console.log('SocialCallbackLogin useEffect:',{socialCode,state,corpId,tenantId,redirect_uri,source})
        if(source === 'dingtalkh5'){//钉钉授权登录
            dd.getAuthCode({
                // @ts-ignore
                corpId,
                success: (res: { code: string }) => {
                    console.log('success',res)
                    const { code } = res;
                    const data = {source,socialCode:code,socialState:state,tenantId,grantType: 'social'}
                    handleSocialLogin(data)
                },
                fail: () => {
                    console.log('fail')
                    message.success("授权失败！");
                },
                complete: () => {},
            });
        }else{
            const data = {source,socialCode:socialCode,socialState:state,tenantId,grantType: 'social'}
            handleSocialLogin(data)
        }
    }, [source]);
    return (
        <PageLoading tip="授权中"></PageLoading>
    )
}

export default SocialCallbackLogin;